import json
from datetime import datetime, timedelta
from time import sleep
import pandas as pd
import re
import requests
from fontTools.ttLib import TTFont
import pytesseract
from reportlab.graphics import renderPM
from fontTools.pens.reportLabPen import ReportLabPen
from reportlab.graphics.shapes import Path, Group, Drawing
from reportlab.lib import colors
from PIL import Image
import cv2

pytesseract.pytesseract.tesseract_cmd = r'D:\software\Tesseract-OCR\tesseract.exe'

headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'Connection': 'keep-alive',
    'Cookie': '_lxsdk_cuid=18bb8e54a52c8-05d74dafedd255-4c657b58-1fa400-18bb8e54a52c8; WEBDFPID=575uyu2zuv49544xz7y888wu6w1y3z9681yy1v31uwz979583021x4y2-2014974199294-1699614198574MQISOUIfd79fef3d01d5e9aadc18ccd4d0c95072811; token=AgHgH4JeCsL56Wf0sTuGdNG58jvtzYIOfuviDdrFBgyDcdDJTIzTi7sSEjEctiHF0QHRcy5oEU6X3AAAAAAaHAAAEQ13krTAkT10BgOiQ4Au66X2tOgGX9KxfIgLFdRmsoksklfSKQrJHUly90LD7qmb; uuid=18bb8e54a52c8-05d74dafedd255-4c657b58-1fa400-18bb8e54a52c8; Hm_lvt_703e94591e87be68cc8da0da7cbd0be2=1699614237,1700572070; Hm_lpvt_703e94591e87be68cc8da0da7cbd0be2=1700572312; _lxsdk=18bb8e54a52c8-05d74dafedd255-4c657b58-1fa400-18bb8e54a52c8; _lx_utm=utm_source%3DBaidu%26utm_medium%3Dorganic; _lxsdk_s=18bf1f19731-200-57b-4e5%7C%7C101',
    'Host': 'piaofang.maoyan.com',
    'Referer': 'https://piaofang.maoyan.com/dashboard/movie?date=2023-11-01&movieId=1466204',
    'Sec-Ch-Ua': '"Microsoft Edge";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
    'Sec-Ch-Ua-Mobile': '?0',
    'Sec-Ch-Ua-Platform': "Windows",
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0',
    'X-For-With': '4s47ITaYu+yQrNmzTgtmRUqG4nVyamtVLs3dxw3W9Vr4vfeW7rpXVAQY9CQh5nsufc6WxwRrBmRzN01Fv4X9eO8QVWp5KMNkVOjxP6ckVZtzH2PCc53PP6bQzWK7YtemEaY/89UYdD4NsSg7LiBtEg/FSldlab1tl2zCMtQFZxb26Uqx6ylGsK5iyKNYCMWOh+i8CWNrmobH7XkT/eM74w=='
}

url = 'https://piaofang.maoyan.com/dashboard-ajax/movie'

data_list = []
date_list = []


def create_date_list():
    diff_days = (datetime.now().date() - datetime.strptime('20231101', '%Y%m%d').date()).days
    for i in range(1, diff_days + 1):
        date = (datetime.now().date() - timedelta(days=i)).strftime('%Y%m%d')
        date_list.append(date)


def download_woff(woff_url):
    woff_headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0',
    }

    woff_resp = requests.get(woff_url, headers=woff_headers)
    with open("../static/font/mao_yan.woff", "wb") as code:
        code.write(woff_resp.content)
        code.flush()


def decode_font():
    mao_yan_font = TTFont('../static/font/mao_yan.woff')
    gs = mao_yan_font.getGlyphSet()
    for i in mao_yan_font.getGlyphNames():
        g = gs[i]
        pen = ReportLabPen(gs, Path(fillColor=colors.red, strokeWidth=7))
        g.draw(pen)
        w, h = 2100, 2100
        g = Group(pen.path)
        g.translate(300, 300)
        d = Drawing(w, h)
        d.add(g)
        image_file = '../static/img' + "/" + i + ".png"
        renderPM.drawToFile(d, image_file, 'png')
        img = cv2.imread(image_file, -1)
        height, width = img.shape[:2]
        # 缩小图像
        size = (int(w * 0.05), int(h * 0.05))
        img = cv2.resize(img, size, cv2.INTER_AREA)
        cv2.imwrite(image_file, img)
        image_buffer = Image.open(image_file)
        mark_img = Image.new('RGBA', size, (255, 0, 0, 0))
        mark_img.paste(image_buffer, (0, 0))
        mark_img.save(image_file)
    img_list = mao_yan_font.getGlyphNames()[1:-1]
    num_map = {}
    for i in img_list:
        image = Image.open('../static/img/%s.png' % i)
        image = image.convert('L')
        text = pytesseract.image_to_string(image, lang='chi_sim',
                                           config=r'-c tessedit_char_whitelist=0123456789 --psm 6')
        num_map[i] = text.replace('\n', '')[0]
    return num_map


def decode_num(code, num_map):
    code_list = code.split('.')
    num = []
    for i in code_list:
        num_code_list = re.findall('&#x(\w{4});', i)
        num_list = []
        for j in num_code_list:
            num_code = 'uni' + j.upper()
            num_list.append(num_map[num_code])
        num.append(''.join(num_list))
    return '.'.join(num)


def req_data():
    for i in date_list:
        params = {
            'showDate': i,
            'movieId': '1466204',
            'orderType': '0',
            'uuid': '18bb8e54a52c8-05d74dafedd255-4c657b58-1fa400-18bb8e54a52c8',
            'timeStamp': '1700572426765',
            'User-Agent': 'TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzExOS4wLjAuMCBTYWZhcmkvNTM3LjM2IEVkZy8xMTkuMC4wLjA=',
            'index': '882',
            'channelId': '40009',
            'sVersion': '2',
            'signKey': '1129721d872502a4374d069c85ffb292'
        }
        response = requests.get(url, headers=headers, params=params)
        json_data = json.loads(response.content.decode())
        font_style = json_data.get('fontStyle', '')
        woff_url = re.findall('url\("(.*?\.woff)"\)', font_style)[0].split(',')[-1]
        woff_url = 'https:' + woff_url[5:]
        download_woff(woff_url)
        num_map = decode_font()
        get_data(json_data, num_map)
        sleep(1)


def get_data(json_data, mao_yan_num_map):
    movie_list = json_data.get('movieList', {}).get('list', [])
    cur_date = json_data.get('calendar', {}).get('selectDate', '')
    for i in range(len(movie_list)):
        movie_name = movie_list[i].get('movieInfo', {}).get('movieName', '')
        movie_box_split_unit = decode_num(movie_list[i].get('boxSplitUnit', {}).get('num', ''), mao_yan_num_map)
        movie_box_rate = movie_list[i].get('boxRate', '')
        movie_avg_seat = movie_list[i].get('avgSeatView', '')
        movie_avg_show = movie_list[i].get('avgShowView', '')
        movie_show_count = movie_list[i].get('showCount', 0)
        movie_show_count_rate = movie_list[i].get('showCountRate', '')
        row = [movie_name, movie_box_split_unit, movie_box_rate, movie_avg_seat, movie_avg_show, movie_show_count,
               movie_show_count_rate, cur_date]
        data_list.append(row)


def save_data_to_csv():
    df = pd.DataFrame(data_list, columns=['movie_name', 'movie_box_split_unit', 'movie_box_rate', 'movie_avg_seat',
                                          'movie_avg_show', 'movie_show_count', 'movie_show_count_rate', 'cur_date'])
    df.to_csv('../static/data/movie_box_rate.csv', encoding='utf-8', index=None)


if __name__ == '__main__':
    create_date_list()
    req_data()
    save_data_to_csv()
